<template>
  <div>
    <div ref="quoteTable" id="quote-table">
      <table border="1">
        <thead>
          <tr>
            <th>Item</th>
            <th>Description</th>
            <th>Price</th>
            <th>Quantity</th>
            <th>Total</th>
          </tr>
        </thead>
        <tbody>
          <tr v-for="(item, index) in items" :key="index">
            <td>{{ item.name }}</td>
            <td>{{ item.description }}</td>
            <td>{{ item.price }}</td>
            <td>{{ item.quantity }}</td>
            <td>{{ (item.price * item.quantity).toFixed(2) }}</td>
          </tr>
        </tbody>
      </table>
    </div>
    <button @click="exportToExcel">Export to Excel</button>
    <button @click="exportToPDF">Export to PDF</button>
  </div>
</template>

<script>
import * as XLSX from 'xlsx';
import jsPDF from 'jspdf';
import 'jspdf-autotable';
import { saveAs } from 'file-saver';
import html2canvas from 'html2canvas';
import * as XLSXStyle from 'xlsx-style-vite';

export default {
  data() {
    return {
      items: [
        { name: 'Item 1', description: 'Description 1', price: 10, quantity: 2 },
        { name: 'Item 2', description: 'Description 2', price: 20, quantity: 3 },
        // 添加更多报价单数据
      ],
    };
  },
  methods: {
    sheet2blob(sheet, sheetName) {
      sheetName = sheetName || 'sheet1';
      var workbook = {
          SheetNames: [sheetName],
          Sheets: {},
      };
      workbook.Sheets[sheetName] = sheet; // 生成excel的配置项

      // 下载这里一定要用 xlsx-style 的write() 方法才可以使导出excel表格带样式
      var wbout = XLSXStyle.write(workbook, { type: 'buffer' });
      var blob = new Blob([wbout], {
          type: 'application/octet-stream',
      }); // 字符串转ArrayBuffer

      return blob;
  },
  openDownloadDialog(url, saveName) {
    if (typeof url == 'object' && url instanceof Blob) {
        url = URL.createObjectURL(url); // 创建blob地址
    }
    var aLink = document.createElement('a');
    aLink.href = url;
    aLink.download = saveName || ''; // HTML5新增的属性，指定保存文件名，可以不要后缀，注意，file:///模式下不会生效
    var event;
    if (window.MouseEvent) event = new MouseEvent('click');
    else {
        event = document.createEvent('MouseEvents');
        event.initMouseEvent(
            'click',
            true,
            false,
            window,
            0,
            0,
            0,
            0,
            0,
            false,
            false,
            false,
            false,
            0,
            null
        );
    }
    aLink.dispatchEvent(event);
},
    exportToExcel() {
      // // const worksheet = XLSX.utils.json_to_sheet(this.items);
      // // const workbook = XLSX.utils.book_new();
      // // XLSX.utils.book_append_sheet(workbook, worksheet, 'Quote Sheet');
      // // XLSX.writeFile(workbook, 'quote.xlsx');
      // var table_elt = document.getElementById("quote-table");

      // // Extract Data (create a workbook object from the table)
      // var workbook = XLSX.utils.table_to_book(table_elt);

      // // Process Data (add a new row)
      // var ws = workbook.Sheets["Sheet1"];
      // XLSX.utils.sheet_add_aoa(ws, [["Created "+new Date().toISOString()]], {origin:-1});

      // // Package and Release Data (`writeFile` tries to write and save an XLSB file)
      // XLSX.writeFile(workbook, "Report.xlsb");
      let listName = [
        ["资产出库单"],
        [
          "编号:",
          val.No,
          null,
          "日期:",
          val.Time,
          null,
          "处理人:",
          val.UserName,
        ],
        ["备注:", val.remark],
        ["列表:"],
        [
          "序号",
          "编码",
          "类别",
        ],
      ];
      let dataList = [];
　　　 //将动态内容遍历，不懂请看另一篇,data即是动态数据
     data.map((item, index) => {
        dataList.push([
          index + 1 + "",
          item.id ? item.id : " ",
          item.type ? item.type : " ",
        ]);
      });
      let footer = [
        [],
        ["签名:", null, null, null, null, "签字时间:", null, null],
      ];
      // 初始化一个excel文档，此时需要传入数据
　　　 //aoa_to_sheet方法是将数组数据转excel，json及其他方法可以去github查看 

      let ws = XLSX.utils.aoa_to_sheet([...listName, ...dataList, ...footer]);
      // console.log(ws)

　　　 // 如果需要修改的单元格较少，可以直接使用styleAll方式，按如下面的方式进行修改，这里的遍历与循环是为了拼凑字符串，如'A1'
      // let styleAll = ["A1", "A2", "B2", "D2", "E2", "G2", "H2","A3","B3","A4",];
      ["A", "B", "C", "D", "E", "F", "G", "H"].map((item) => {
        for (let i = 1; i < 6 + dataList.length; i++) {
          let str = (item + i).toString();
          if (ws[str]) {
            if (i < 5 || i > dataList.length + 6) {
              ws[str].s = {
                font: {
                  name: "宋体",
                  sz: 12,
                  color: {
                    auto: 1,
                  },
                },
                alignment: {
                  /// 自动换行
                  wrapText: 1,
                  // 居中
                  horizontal: "center",
                  vertical: "center",
                  indent: 0,
                },
              };
            } else {
              ws[str].s = {
                font: {
                  name: "宋体",
                  sz: 12,
                  color: {
                    auto: 1,
                  },
                },
                border: {
                  color: {
                    auto: 1,
                  },
                  top: {
                    style: i === 5 ? "thin" : null,
                  },
                  bottom: {
                    style: i === 5 + dataList.length ? "thin" : null,
                  },
                  left: {
                    style: item === "A" ? "thin" : null,
                  },
                  right: {
                    style: item === "H" ? "thin" : null,
                  },
                },
                alignment: {
                  /// 自动换行
                  wrapText: 1,
                  // 居中
                  horizontal: "center",
                  vertical: "center",
                  indent: 0,
                },
              };
            }
          }
        }
      });
      ws["!merges"] = [
        {
          s: { c: 0, r: 0 },
          e: { c: 8, r: 0 },
        },
        {
          s: { c: 1, r: 1 },
          e: { c: 2, r: 1 },
        },
        {
          s: { c: 4, r: 1 },
          e: { c: 5, r: 1 },
        },
        {
          s: { c: 1, r: 2 },
          e: { c: 8, r: 2 },
        },
        {
          s: { c: 1, r: 3 },
          e: { c: 8, r: 3 },
        },
        {
          s: { c: 0, r: 5 + dataList.length },
          e: { c: 8, r: 5 + dataList.length },
        },
        {
          s: { c: 1, r: 6 + dataList.length },
          e: { c: 4, r: 6 + dataList.length },
        },
        {
          s: { c: 6, r: 6 + dataList.length },
          e: { c: 7, r: 6 + dataList.length },
        },
      ];
      ws["!rows"] = [
        {
          hpx: 30,
        },
        {
          hpx: 18,
        },
        {
          hpx: 30,
        },
        {
          hpx: 18,
        },
        {
          hpx: 18,
        },
        {
          hpx: 18,
        },
        {
          hpx: 18,
        },
        {
          hpx: 18,
        },
        {
          hpx: 18,
        },
        {
          hpx: 18,
        },
        {
          hpx: 18,
        },
        {
          hpx: 18,
        },
      ];
      ws["!cols"] = [
        {
          wpx: 80,
        },
        {
          wpx: 80,
        },
        {
          wpx: 80,
        },
        {
          wpx: 80,
        },
        {
          wpx: 80,
        },
        {
          wpx: 80,
        },
        {
          wpx: 80,
        },
      ];
      openDownloadDialog(sheet2blob(ws), "出库导出.xlsx");
    },
    async exportToPDF() {
      const table = this.$refs.quoteTable;
      const canvas = await html2canvas(table);
      const imgData = canvas.toDataURL('image/png');
      const pdf = new jsPDF('p', 'mm', 'a4');
      const imgWidth = 190; // 设置图片宽度
      const imgHeight = (canvas.height * imgWidth) / canvas.width; // 保持图片比例
      pdf.addImage(imgData, 'PNG', 10, 10, imgWidth, imgHeight);
      pdf.save('quote.pdf');
    },
  },
};
</script>

<style scoped>
#quote-table {
  width: 100%;
  max-width: 800px;
  margin: 0 auto;
}

table {
  width: 100%;
  border-collapse: collapse;
}

th {
  background-color: aquamarine;
}

th, td {
  padding: 8px;
  text-align: left;
}
</style>